package org.elasticsearch;

import org.elasticsearch.http.netty4.Netty4HttpRequestHandler;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInitializer;
import io.netty.handler.codec.ByteToMessageDecoder;
import io.netty.handler.codec.http.*;

/**
 * Created by Administrator on 2017/7/4 0004.
 */
public class HttpChannelHandler extends ChannelInitializer<Channel> {

    private final Netty4HttpServerTransport transport;
    private final Netty4HttpRequestHandler requestHandler;

    protected HttpChannelHandler(
        final Netty4HttpServerTransport transport,
        final boolean detailedErrorsEnabled) {
        this.transport = transport;
        this.requestHandler = new Netty4HttpRequestHandler(transport, detailedErrorsEnabled);
    }

    @Override
    protected void initChannel(Channel ch) throws Exception {

        final HttpRequestDecoder decoder = new HttpRequestDecoder();
        decoder.setCumulator(ByteToMessageDecoder.COMPOSITE_CUMULATOR);
        ch.pipeline().addLast("decoder", decoder);
        ch.pipeline().addLast("decoder_compress", new HttpContentDecompressor());
        ch.pipeline().addLast("encoder", new HttpResponseEncoder());
        final HttpObjectAggregator aggregator = new HttpObjectAggregator(1024*1024*100);

        ch.pipeline().addLast("aggregator", aggregator);
        ch.pipeline().addLast("handler", requestHandler);
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        super.exceptionCaught(ctx, cause);
    }

}
